#include "SearchEngineServer.h"
#include <iostream>


/* class MyTask
{
public:
    MyTask(const string &msg, const TcpConnectionPtr &con)
    : _msg(msg)
    , _con(con)
    {

    }
    void process()
    {
        //将业务逻辑在此处添加
        _con->sendInLoop("hello\n");
    }
private:
    string _msg;
    TcpConnectionPtr _con;
    //KeyRecommander &_recommander; 
}; */


SearchEngineServer::SearchEngineServer(size_t threadNum,size_t queSize,const string &ip,short port)  //构造函数
: _pool(threadNum,queSize)
, _tcpServer(ip,port)
//, _keyRecommander()
{

}

SearchEngineServer::~SearchEngineServer()
{

}

void SearchEngineServer::start()   //开始提供服务
{
    _pool.start();
    using namespace std::placeholders;
    _tcpServer.setAllCallback(std::bind(&SearchEngineServer::onConnection,this,_1)
                              ,std::bind(&SearchEngineServer::onMessage,this,_1)
                              ,std::bind(&SearchEngineServer::onClose,this,_1));
    _tcpServer.start();
}

void SearchEngineServer::stop()
{
    _pool.stop();
    _tcpServer.stop();
}


void SearchEngineServer::onConnection(const TcpConnectionPtr &conn)  //被注册回调函数，提供给TcpServer使用
{
    cout << conn->toString() << "has connected!" << endl;
}
void SearchEngineServer::onMessage(const TcpConnectionPtr & conn)    //被注册回调函数，提供给TcpServer使用
{
    string msg = conn->receive();  //接收客户端数据
    msg = msg.substr(0, msg.length() - 1);
    cout << msg << endl;
    json jsonObj = json::parse(msg);
    //cout << jsonObj["command"] << " " << jsonObj["data"] << endl;
    cout << ">> recv msg from client " << msg << endl;

    //接收到客户端的msg之后，进行业务逻辑的处理
    //MyTask task(msg,conn);
    unique_ptr<RedisCache> pRedis(new RedisCache());
    if(!pRedis->connect("127.0.0.1",6379))
    {
        std::cerr << "connect error!" << endl;
        return;
    }
    if(jsonObj["command"] == "rec")
    {
        string resValue = pRedis->getKey(jsonObj["data"]);
        if(resValue!= "")
        {
            cout << "success" << endl;
            conn->sendInLoop("rec\n");
            conn->sendInLoop(resValue);
        }
        else{
            _keyRecommander.setQueryWord(jsonObj["data"]);
            _keyRecommander.setTcpConnectionPtr(conn);
            _pool.addTask(std::bind(&KeyRecommander::execute, _keyRecommander));
        }
    }
    else if(jsonObj["command"] == "query")
    {
        string resValue = pRedis->getWeb(jsonObj["data"]);
        if(resValue != "")
        {
            cout << "success" << endl;
            conn->sendInLoop("query\n");
            conn->sendInLoop(resValue);
        }
        else{
            _webSearcher.setKeys(jsonObj["data"]);
            _webSearcher.setTcpConnectionPtr(conn); 
            _pool.addTask(std::bind(&WebPageSearcher::doQuery, _webSearcher));
        }   
    }      
}
void SearchEngineServer::onClose(const TcpConnectionPtr & conn)      //被注册回调函数，提供给TcpServer使用
{
    cout << conn->toString() << "has closed" << endl; 
}



